const { app, BrowserWindow, protocol } = require('electron');
const path = require('path');
const { argv } = require('process');
// console.log(app.getPath('userData'));

// ==================== 应用配置日志 ====================
console.log('🔧 应用配置初始化...');
// 关闭 GPU 磁盘缓存，避免报错
app.commandLine.appendSwitch('disable-gpu-disk-cache')
app.commandLine.appendSwitch('disk-cache-size', '1')
app.commandLine.appendSwitch('--disable-software-rasterizer')
app.commandLine.appendSwitch('--disable-gpu')
app.commandLine.appendSwitch('--disable-gpu-compositing')
app.setPath('userData', path.join(__dirname, 'userData'))
console.log('✅ GPU配置已应用，用户数据路径已设置');

// 中国主流安卓设备的UserAgent数组
const chineseAndroidUserAgents = [
    // 华为设备
    "Mozilla/5.0 (Linux; Android 12; HarmonyOS; HUAWEI P50 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 11; HUAWEI Mate 40 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 10; HUAWEI nova 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36",

    // 小米设备
    "Mozilla/5.0 (Linux; Android 13; 2211133C) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 12; M2012K11AC) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 11; Mi 11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36",

    // OPPO设备
    "Mozilla/5.0 (Linux; Android 13; CPH2449) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 12; PERM00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 11; OPPO Find X3 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Mobile Safari/537.36",

    // vivo设备
    "Mozilla/5.0 (Linux; Android 13; V2227A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 12; V2145A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 11; vivo X70 Pro+) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36",

    // 一加设备
    "Mozilla/5.0 (Linux; Android 13; CPH2423) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 12; OnePlus 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",

    // 荣耀设备
    "Mozilla/5.0 (Linux; Android 12; HONOR 70) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (Linux; Android 11; HONOR Magic4 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36"
];

// 获取随机UserAgent
const getRandomUserAgent = () => {
    const randomIndex = Math.floor(Math.random() * chineseAndroidUserAgents.length);
    return chineseAndroidUserAgents[randomIndex];
};

// 生成随机的中国IP地址段
const getRandomChineseIP = () => {
    // 中国主要IP段
    const chineseIPRanges = [
        // 北京
        { start: [1, 202, 97], end: [1, 202, 127] },
        { start: [27, 115, 0], end: [27, 115, 255] },
        { start: [42, 62, 0], end: [42, 62, 255] },
        { start: [58, 16, 0], end: [58, 63, 255] },
        { start: [59, 108, 0], end: [59, 108, 255] },

        // 上海
        { start: [61, 152, 0], end: [61, 159, 255] },
        { start: [101, 227, 0], end: [101, 227, 255] },
        { start: [116, 228, 0], end: [116, 231, 255] },
        { start: [180, 168, 0], end: [180, 168, 255] },

        // 广东
        { start: [14, 215, 0], end: [14, 215, 255] },
        { start: [59, 37, 0], end: [59, 44, 255] },
        { start: [113, 108, 0], end: [113, 111, 255] },
        { start: [183, 60, 0], end: [183, 63, 255] },

        // 浙江
        { start: [60, 191, 0], end: [60, 191, 255] },
        { start: [115, 238, 0], end: [115, 239, 255] },
        { start: [125, 210, 0], end: [125, 213, 255] },

        // 江苏
        { start: [49, 77, 0], end: [49, 77, 255] },
        { start: [58, 192, 0], end: [58, 223, 255] },
        { start: [112, 5, 0], end: [112, 7, 255] },

        // 山东
        { start: [60, 216, 0], end: [60, 223, 255] },
        { start: [123, 232, 0], end: [123, 235, 255] },

        // 湖北
        { start: [59, 172, 0], end: [59, 175, 255] },
        { start: [113, 57, 0], end: [113, 59, 255] },

        // 四川
        { start: [60, 255, 0], end: [60, 255, 255] },
        { start: [125, 64, 0], end: [125, 71, 255] },

        // 河南
        { start: [42, 224, 0], end: [42, 239, 255] },
        { start: [61, 168, 0], end: [61, 171, 255] },

        // 福建
        { start: [58, 22, 0], end: [58, 23, 255] },
        { start: [112, 111, 0], end: [112, 111, 255] },

        // 湖南
        { start: [59, 62, 0], end: [59, 63, 255] },
        { start: [113, 240, 0], end: [113, 247, 255] },
    ];

    const randomRange = chineseIPRanges[Math.floor(Math.random() * chineseIPRanges.length)];
    const { start, end } = randomRange;

    const ip = [
        Math.floor(Math.random() * (end[0] - start[0] + 1)) + start[0],
        Math.floor(Math.random() * (end[1] - start[1] + 1)) + start[1],
        Math.floor(Math.random() * (end[2] - start[2] + 1)) + start[2],
        Math.floor(Math.random() * 254) + 1
    ];

    return ip.join('.');
};

// 生成随机的地理位置相关请求头
const getRandomLocationHeaders = () => {
    const cities = [
        '北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都',
        '重庆', '天津', '西安', '沈阳', '长沙', '郑州', '济南', '大连'
    ];
    const provinces = [
        'Beijing', 'Shanghai', 'Guangdong', 'Zhejiang', 'Jiangsu', 'Hubei',
        'Sichuan', 'Chongqing', 'Tianjin', 'Shaanxi', 'Liaoning', 'Hunan'
    ];

    const randomCity = cities[Math.floor(Math.random() * cities.length)];
    const randomProvince = provinces[Math.floor(Math.random() * provinces.length)];

    return {
        'X-Forwarded-For': getRandomChineseIP(),
        'X-Real-IP': getRandomChineseIP(),
        'X-Client-IP': getRandomChineseIP(),
        'CF-Connecting-IP': getRandomChineseIP(), // Cloudflare
        'True-Client-IP': getRandomChineseIP(),
        'X-Originating-IP': getRandomChineseIP(),
        'X-Cluster-Client-IP': getRandomChineseIP(),
        'X-User-Location': randomCity,
        'X-User-Region': randomProvince,
        'Via': `1.1 proxy${Math.floor(Math.random() * 999) + 1}.example.com:8080`,
    };
};

// 获取随机延时（5-10秒）
const getRandomDelay = () => {
    return Math.floor(Math.random() * 5000) + 5000; // 3000-5000ms
};

// 创建带完整隐私保护和代理的窗口
async function createIncognitoWindow(windowId) {
    console.log(`\n📱 [窗口${windowId}] 开始创建隐私保护窗口...`);
    
    // 获取代理信息
    const win = new BrowserWindow({
        width: 375,
        height: 812,
        x: process.env.PROCESS_ARG * 375, // 水平排列窗口
        y: 0,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            partition: `temp:incognito-${windowId}`, // 临时session，关闭后自动清理
            allowRunningInsecureContent: true, // 允许不安全内容
            experimentalFeatures: true
        },
        show: argv[2], // 先不显示窗口
        focusable: false, // 窗口不可获取焦点
        skipTaskbar: true, // 不在任务栏显示
        alwaysOnTop: false, // 不置顶
        title: `访问窗口 ${windowId}`
    });

    console.log(`✅ [窗口${windowId}] 窗口对象创建成功`);

    // 获取session并设置代理
    const ses = win.webContents.session;
    console.log(`🧹 [窗口${windowId}] 开始清理session数据...`);
    
    // 在应用启动时清理
    await ses.clearCache()
    await ses.clearData()
    await ses.clearAuthCache()
    // 清除所有存储数据
    await ses.clearStorageData();
    console.log(`✅ [窗口${windowId}] session数据清理完成`);

    // 设置随机UserAgent
    const randomUA = getRandomUserAgent();
    win.webContents.setUserAgent(randomUA);

    // 添加页面加载事件监听
    win.webContents.on('did-start-loading', () => {
        console.log(`🔄 [窗口${windowId}] 页面开始加载...`);
    });

    win.webContents.on('did-finish-load', () => {
        console.log(`✅ [窗口${windowId}] 页面加载完成，准备执行自动点击...`);
        // 随机点击逻辑
        const delay = Math.floor(Math.random() * 5000) + 1000; // 1-5秒
        setTimeout(() => {
            if (!win || win.isDestroyed()) return;
            win.webContents.executeJavaScript(`
                (function() {
                    const elements = document.querySelectorAll('a.itemList');
                    if (elements.length > 0) {
                        const randomEl = elements[Math.floor(Math.random() * elements.length)];
                        randomEl.click();
                        console.log("🎯 已自动点击一个随机元素:", randomEl);
                    } else {
                        console.log("⚠️ 没有找到可点击的元素");
                    }
                })();
            `).catch(err => console.error("点击脚本执行失败:", err));
        }, delay);
    });

    win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
        console.error(`❌ [窗口${windowId}] 页面加载失败:`, errorCode, errorDescription, validatedURL);
    });

    win.webContents.on('crashed', () => {
        console.error(`💥 [窗口${windowId}] 窗口崩溃`);
    });

    // 拦截所有请求并添加伪造的IP头
    ses.webRequest.onBeforeSendHeaders((details, callback) => {
        const headers = getRandomLocationHeaders();

        // 合并原有header和新header
        Object.assign(details.requestHeaders, headers);

        // 删除可能泄露真实身份的header
        delete details.requestHeaders['X-Forwarded-Host'];
        delete details.requestHeaders['X-Original-URL'];

        // 添加随机的Accept-Language
        const languages = ['zh-CN,zh;q=0.9,en;q=0.8', 'zh-CN,zh;q=0.8,en;q=0.7', 'zh-CN,zh;q=0.9'];
        details.requestHeaders['Accept-Language'] = languages[Math.floor(Math.random() * languages.length)];

        // 添加随机的DNT设置
        details.requestHeaders['DNT'] = Math.random() > 0.5 ? '1' : '0';

        // 添加常见的浏览器头
        details.requestHeaders['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        details.requestHeaders['Accept-Encoding'] = 'gzip, deflate, br';
        details.requestHeaders['Cache-Control'] = 'no-cache';
        details.requestHeaders['Pragma'] = 'no-cache';

        callback({ requestHeaders: details.requestHeaders });
    });

    console.log(`✅ [窗口${windowId}] 隐私保护配置完成`);
    return win;
}


function getRandomUrl(urls) {
    // 计算总权重
    const totalWeight = urls.reduce((sum, item) => sum + (item.weight || 1), 0);

    // 生成随机数
    const random = Math.random() * totalWeight;

    // 根据权重选择URL
    let currentWeight = 0;
    for (const item of urls) {
        currentWeight += (item.weight || 1);
        if (random <= currentWeight) {
            return item.url;
        }
    }

    // 如果没有权重或出现异常，返回最后一个URL
    return urls[urls.length - 1]?.url;
}

// 主应用逻辑 - 按照新的流程
app.whenReady().then(async () => {
    console.log('\n🚀 ==================== 应用启动 ====================');
    console.log('📱 Electron应用正在启动...');
    
    // 发送ready信号给PM2，表示应用已准备就绪
    if (process.send) {
        process.send('ready');
        console.log('✅ PM2信号已发送: ready');
    }

    const url = "https://lc.reso.top/static/wh5.json";
    console.log('🌐 配置URL:', url);
    
    // 设置要创建的窗口数量
    const windowCount = 1000000000000; // 可以修改这个数量
    console.log(`📊 目标窗口数量: ${windowCount.toLocaleString()}`);

    console.log('\n🔄 ==================== 开始批量创建窗口 ====================');

    // 主循环：请求代理IP → 获取URL → 创建窗口 → 等待5秒
    for (let i = 1; i <= windowCount; i++) {
        try {
            console.log(`\n📋 ==================== 窗口 ${i} 处理流程 ====================`);
            
            // 步骤1: 获取URL配置
            console.log(`🔍 [窗口${i}] 步骤1: 正在获取URL配置...`);
            const resp = await fetch(url).then(response => response.json());
            console.log(`📋 [窗口${i}] 获取到 ${resp.urls.length} 个可用URL`);
        
            // 步骤2: 创建隐私保护窗口
            console.log(`🏗️ [窗口${i}] 步骤2: 正在创建隐私保护窗口...`);
            const win = await createIncognitoWindow(i);

            // 步骤3: 选择并加载URL
            let sec = getRandomDelay();
            const element = getRandomUrl(resp.urls);
            console.log(`🎯 [窗口${i}] 步骤3: 已选择目标URL: ${element}`);
            
            console.log(`📥 [窗口${i}] 正在加载页面...`);
            await win.loadURL(element);
            console.log(`✅ [窗口${i}] 页面加载完成`);
            
            console.log(`⏰ [窗口${i}] 等待 ${sec}ms 后继续下一个窗口...`);
            await new Promise(resolve => setTimeout(resolve, sec));

            // 步骤4: 清理和关闭
            if (!win.isDestroyed()) {
                console.log(`🧹 [窗口${i}] 步骤4: 开始清理session数据...`);
                try {
                    const ses = win.webContents.session;
                    await ses.clearCache();
                    await ses.clearStorageData();
                    await ses.clearAuthCache();
                    console.log(`✅ [窗口${i}] session数据清理完成`);
                } catch (error) {
                    console.error(`❌ [窗口${i}] session清理失败:`, error.message);
                }
                
                win.close();
                console.log(`🔒 [窗口${i}] 窗口已关闭`);
            }

            console.log(`✅ [窗口${i}] 处理流程完成`);

        } catch (error) {
            console.error(`\n❌ ==================== 窗口 ${i} 处理失败 ====================`);
            console.error(`💥 错误详情:`, error.message);
            console.error(`📍 错误位置:`, error.stack?.split('\n')[1] || '未知');
            console.log(`⏰ 等待5秒后继续下一个窗口...`);
            // 即使失败也等待5秒，保持流程一致性
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
    }

    console.log(`\n🎉 ==================== 批量任务完成 ====================`);
    console.log(`📊 总计处理窗口数: ${windowCount.toLocaleString()}`);
    console.log(`✅ 所有窗口创建任务已完成！`);
});

// 应用退出处理
app.on('window-all-closed', () => {
    console.log('🔒 所有窗口已关闭，准备退出应用...');
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    console.log('🔄 应用被激活，重新创建窗口...');
    if (BrowserWindow.getAllWindows().length === 0) {
        // 重新创建窗口
        app.emit('ready');
    }
});

console.log('🔧 启动参数:', argv[2]);
